<!--
 * @Author: tenet 18742176629@163.com
 * @Date: 2024/6/25 下午4:52
 * @LastEditors: tenet 18742176629@163.com
 * @LastEditTime: 2024/6/25 下午4:52
 * @FilePath: G:/block-watch-sys/src/views/package\index.vue
 * @Description: 套餐管理
-->
<template>
  <!-- 查询 -->
  <div class="queryBar">
    <!--    <el-form :inline="true" :model="queryParams" class="demo-form-inline">-->
    <!--      <el-form-item :label="$t('package.PackageName')" style="width: 350px; margin-bottom:0; margin-right: 20px">-->
    <!--        <el-input v-model.trim="queryParams.id" :placeholder="$t('global.PleaseInput') + $t('package.PackageName')"-->
    <!--          clearable />-->
    <!--      </el-form-item>-->
    <!--      <el-form-item :label="$t('package.PackageStatus')" style="width: 350px; margin-bottom: 0; margin-right: 20px">-->
    <!--        <el-select v-model.trim="queryParams.orderStatus"-->
    <!--          :placeholder="$t('global.PleaseSelect') + $t('package.PackageStatus')" clearable>-->
    <!--          <el-option v-for="(item, index) in orderStatusOptions" :key="index" :label="item.label" :value="item.value" />-->
    <!--        </el-select>-->
    <!--      </el-form-item>-->
    <!--      <el-form-item style="margin-bottom: 0">-->
    <!--        <el-button type="primary" :icon="Search" @click="onSubmit(queryParams.id, queryParams.orderStatus)">{{-->
    <!--          $t('button.Search')-->
    <!--          }}</el-button>-->
    <!--        <el-button type="default" :icon="Refresh" plain @click="onReset()">{{ $t('button.Reset') }}</el-button>-->
    <!--      </el-form-item>-->
    <!--    </el-form>-->

    <!--    &lt;!&ndash;    查询按钮&ndash;&gt;-->
    <div class="query_btns">
      <!-- 新增单个套餐 -->
      <el-button type="primary" plain :icon="Plus" size="small" @click="handleCLickDialogTrue('add')">
        {{ $t('button.Add') }}
      </el-button>
    </div>
  </div>


  <el-table :data="tableData" stripe border style="width: 100%; " size="large" v-loading="loading" max-height="700px">

    <el-table-column prop="id" :label="$t('package.PackageId')" width="auto" align="center"></el-table-column>

    <el-table-column prop="categoryName" :label="$t('category.categoryName')" width="auto" align="center"></el-table-column>

    <el-table-column prop="productName" :label="$t('package.PackageName')" width="auto"
                     align="center"></el-table-column>

    <el-table-column prop="fee" :label="$t('package.PackageFee')" width="auto" align="center"></el-table-column>

    <el-table-column prop="months" :label="$t('package.PackageMonths')" width="auto" align="center"></el-table-column>

    <el-table-column prop="type" :label="$t('package.PackageType')" width="auto" align="center">
      <template #default="scope">
        {{ formatProductType(scope.row.type) }}
      </template>
    </el-table-column>

    <el-table-column fixed="right" :label="$t('global.Operation')" width="auto" align="center">
      <template #default="scope">
        <!-- 修改套餐按钮 -->
        <el-button type="success" plain :icon="Edit" size="small" @click="handleCLickDialogTrue('edit', scope.row)">
          {{ $t('button.Edit') }}
        </el-button>
        <!-- 删除套餐按钮 -->
        <el-button type="danger" plain :icon="Delete" size="small" @click="deleteProductBtn(scope.row)">
          {{ $t('button.Del') }}
        </el-button>
      </template>
    </el-table-column>

  </el-table>

  <div class="page">
    <el-pagination v-model:current-page="pageIndex" :page-size="pageSize" layout="total, prev, pager, next"
                   :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
  </div>


  <!-- 新增单个套餐 -- 弹出对话框 -->
  <el-dialog v-model="dialogFormVisible" :title="productForm.formTitle" width="500" @close="closeDialog">
    <el-form :model="productForm">
      <!--      <el-form-item :label="t('package.PackageCategory')" :label-width="formLabelWidth">-->
      <!--        <el-input v-model="productForm.productCategory" autocomplete="off"-->
      <!--          :placeholder="$t('global.PleaseInput') + $t('package.PackageCategory')" @input="productNameHandleInput" />-->
      <!--      </el-form-item>-->
      <el-form-item :label="t('package.PackageCategory')" :label-width="formLabelWidth">
        <el-select v-model.trim="productForm.categoryId" :loading="loading"
                   :placeholder="$t('global.PleaseSelect') + $t('category.category')">
          <el-option v-for="(item, index) in categoryOptions" :key="index" :label="item.name" :value="item.id"
                     @click="changeCategory(item)"/>
        </el-select>
      </el-form-item>
      <el-form-item :label="t('package.PackageName')" :label-width="formLabelWidth">
        <el-input v-model="productForm.productName" autocomplete="off"
                  :placeholder="$t('global.PleaseInput') + $t('package.PackageName')"/>
      </el-form-item>
      <el-form-item :label="t('package.PackageFee')" :label-width="formLabelWidth">
        <el-input type="number" v-model="productForm.fee" autocomplete="off"
                  :placeholder="$t('global.PleaseInput') + $t('package.CostPositive')"
                  @input="ChangeNumValue(productForm.fee)"/>
      </el-form-item>
      <el-form-item :label="t('package.PackageMonths')" :label-width="formLabelWidth">
        <el-input style="width: 50%;" v-model.trim="productForm.months"
                  :placeholder="$t('global.PleaseInput') + $t('package.TimeInt')" @input="updateNumber"/>
        <el-select style="width: 50%;" v-model="productForm.type" :placeholder="$t('package.TimeUnit')">
          <el-option v-model="productForm.type" v-for="item in options" :key="item.value" :label="item.label"
                     :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('global.emailCode')" :label-width="formLabelWidth">
        <el-input style="width: 50%;" v-model="productForm.code"></el-input>
        <el-button style="width: 50%;" @click="getEmailCode" :disabled="isThrottled">
          <span v-show="!isThrottled">
            {{ $t('global.GetCode') }}
          </span>
          <span v-show="isThrottled">
            {{ `${remainingTime}${$t('global.reSendCode')}` }}
          </span>
        </el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCLickDialogFalse()">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="delDialogVisible" :title="productForm.formTitle" width="500" @close="closeDialog">
    <el-form>
      <el-form-item :label="$t('global.emailCode')" :label-width="formLabelWidth">
        <el-input style="width: 50%;" v-model="productForm.code"></el-input>
        <el-button style="width: 50%;" @click="getEmailCode" :disabled="isThrottled">
          <span v-show="!isThrottled">
            {{ $t('global.GetCode') }}
          </span>
          <span v-show="isThrottled">
            {{ `${remainingTime}${$t('global.reSendCode')}` }}
          </span>
        </el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="delDialogVisible = false">
          {{ $t('global.Cancel') }}
        </el-button>
        <el-button type="primary" @click="deleteProductFn">
          {{ $t('global.Submit') }}
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup>
import {ref, onMounted, unref, reactive} from 'vue'
import {Delete, Edit, Message, Plus, Refresh, Search, Upload} from "@element-plus/icons-vue";
import {useI18n} from "vue-i18n";
import {formatTimestamp} from "@/utils/timeStamp";
import {ElPagination, ElMessage, ElTable, ElMessageBox} from "element-plus";
import {getProductList, createProduct, patchProduct, deleteProduct, categoryList, getEmailCodeApi} from '@/require/api.js'
import { useUserStore } from "@/stores";

const userStore = useUserStore();

const {t} = useI18n();

// 查询参数
const queryParams = reactive([
  {
    id: '',
    orderStatus: ''
  }
])

const pageSize = ref(10)
const pageIndex = ref(1)
const total = ref(0)
const tableData = ref([])

// 新增或修改套餐 弹出的对话框中使用
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'

const productForm = reactive({
  id: null,
  formTitle: null,
  productName: null,
  productCategory: null,
  fee: null,
  months: null,
  type: null,
  categoryId: null,
  categoryName: null,
  code: null
})

// 下拉菜单
const value = ref('')

const categoryOptions = ref([]); // 类别

// 获取类别名称
async function changeCategory(item) {
  productForm.categoryName = item.name;
}


// 获取类别
async function getCategoryList() {
  try {
    const {code, data, message} = await categoryList()
    if (code === 200) {
      categoryOptions.value = data.list;
    }
  } catch (e) {
    console.log(e)
  }
}

const options = [
  {
    value: '1',
    label: t('package.Years'),
  },
  {
    value: '2',
    label: t('package.Months'),
  },
  {
    value: '3',
    label: t('package.Days'),
  },
  {
    value: '4',
    label: t('package.Hours'),
  }
]


onMounted(() => {
  getList();
  getCategoryList();
});

const loading = ref(false);

const readyPatchObj = ref({})

// 点击按钮方法
const handleCLickDialogTrue = (val1, val2) => {
  dialogFormVisible.value = true;
  handleType.value = val1

  switch (val1) {
    case 'add':
      // 点击添加套餐按钮
      productForm.formTitle = t('package.AddPackage')
      productForm.productName = ''
      productForm.fee = ''
      productForm.months = 1
      productForm.type = '1'

      break;
    case 'edit':
      // 点击修改套餐按钮
      productForm.formTitle = t('package.EditPackage')
      productForm.productName = val2.productName
      productForm.fee = val2.fee
      productForm.months = val2.months
      productForm.type = val2.type
      productForm.id = val2.id
      productForm.categoryId = val2.categoryId;
      break;
    default:
      break;
  }
}

// 点击按钮类型
const handleType = ref('')

// 关闭对话框
function closeDialog() {
  dialogFormVisible.value = false;
  productForm.id = null;
  productForm.formTitle = null;
  productForm.productName = null;
  productForm.productCategory = null;
  productForm.fee = null;
  productForm.months = null;
  productForm.type = null;
  productForm.categoryId = null;
  productForm.categoryName = null;
  productForm.code = null;
};

// 提交
const handleCLickDialogFalse = (val) => {
  switch (handleType.value) {
    case 'add':
      if (productForm.productName == '' || productForm.fee == '') {
        ElMessage.error(t('message.InputAll'))
      } else {
        // 调用添加套餐方法
        createProductBtn()
      }
      break;
    case 'edit':
      if (productForm.productName == '' || productForm.fee == '') {
        ElMessage.error(t('message.InputAll'))
      } else {
        // 调用修改套餐方法
        patchProductBtn()
      }
      break;
    default:
      break;
  }
}

// 检查 productForm.fee 的输入内容
function ChangeNumValue(tmpVal) {
  if (tmpVal) {
    var tmpVal = tmpVal.replace(/[^\d\.]/g, '');
    var reg = /^(0|([1-9]\d*))(\.\d{1,2})?$/; //正则验证保留 最多允许后输入两位小数
    if (!reg.test(tmpVal)) {
      tmpVal = tmpVal + "";
      tmpVal = tmpVal.substring(0, tmpVal.indexOf(".") + 3);
      var n = (tmpVal.split('.')).length - 1;
      if (n > 1) {
        tmpVal = tmpVal.substring(0, tmpVal.indexOf("."));
      }
    }
    return tmpVal + '';
  } else {
    return "";
  }
}

// 处理时间输入
const updateNumber = () => {
  // 尝试将输入字符串转换为数字
  const inputValue = parseFloat(productForm.months);
  // 检查转换是否成功（即输入是否为有效的数字）
  if (!isNaN(inputValue)) {
    productForm.months = inputValue;
  } else {
    // 如果转换失败，可以将 numberValue 重置为 null 或其他默认值
    productForm.months = 1;
  }
}


// 获取套餐列表
async function getList() {
  try {
    loading.value = true
    const {code, data, msg} = await getProductList({
      pageIndex: unref(pageIndex),
      pageSize: unref(pageSize),
    })
    if (code === 200) {
      tableData.value = data.list
      total.value = data.total
    } else {
      ElMessage.error(msg)
    }
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}

// 是否处于节流状态
const isThrottled = ref(false);
// 发送验证码剩余时间
let remainingTime = ref(60);

// 节流函数
function throttle(fn) {
  // 如果处于节流状态，直接返回
  if (isThrottled.value) return;
  isThrottled.value = true;
  fn();
}

// 倒计时函数
function startCountdown(seconds) {
  remainingTime.value = seconds;
  const interval = setInterval(() => {
    remainingTime.value -= 1;
    if (remainingTime.value <= 0) {
      clearInterval(interval);
      isThrottled.value = false;
    }
  }, 1000);
}

// 发送验证码
function getEmailCode(){
  throttle(async () => {
    try {
      const formData = new FormData();
      formData.append('to', userStore.getUserInfo.email);
      await getEmailCodeApi(formData);
      ElMessage.success(t('message.GetCodeSuccess'));
      startCountdown(60);
    } catch(error) {
      console.log('getEmailCodeApi - error', error);
    }
  });
};

// 添加套餐
async function createProductBtn() {
  // const params = {
  //   productName: productForm.productName,
  //   fee: productForm.fee,
  //   months: productForm.months,
  //   type: productForm.type,
  //   categoryId: productForm.categoryId,
  //   categoryName: productForm.categoryName
  // }
  let res = await createProduct(productForm)
  if (res.code == 200) {
    ElMessage.success(t('message.AddSuccess'))
  } else {
    ElMessage.error(res.msg)
  }
  closeDialog();
  // 修改后，再次获取套餐列表信息刷新
  getList();
}

// 修改套餐
async function patchProductBtn() {
  let res = await patchProduct(productForm);
  console.log('res',res);
  if (res.code === 200) {
    ElMessage.success(t('message.EditSuccess'));
  } else {
    ElMessage.error(res.msg);
  }
  closeDialog();
  // 修改后，再次获取套餐列表信息刷新
  getList();
}

const delDialogVisible = ref(false);
const delProductObj = ref({});

// 删除套餐
function deleteProductBtn(rowData) {
  delDialogVisible.value = true;
  productForm.formTitle = t('package.DeletePackage')
  delProductObj.value.id = rowData.id;


  // ElMessageBox.confirm(
  //     t('global.DeleteInfo') + t('message.PleaseInputCode'),
  //     t('global.DeleteInfoImportance'),
  //     {
  //       confirmButtonText: t('global.OK'),
  //       cancelButtonText: t('global.Cancel'),
  //       type: 'warning',
  //     }
  // )
  //     .then(async () => {
  //       let obj = {"id": rowData.id}
  //       // console.log("obj", obj);
  //       let res = await deleteProduct(obj)
  //       // console.log("res", res);

  //       // 修改后，再次获取套餐列表信息刷新
  //       getList();

  //       ElMessage({
  //         type: 'success',
  //         message: t('global.DeleteCompleted'),
  //       })
  //     })
  //     .catch(() => {
  //       ElMessage({
  //         type: 'info',
  //         message: t('global.DeleteCanceled'),
  //       })
  //     })
}

// 删除套餐方法
async function deleteProductFn() {
  let params = {
    "id": delProductObj.value.id,
    "code": productForm.code,
  };
  let res = await deleteProduct(params);
  if (res.code === 200) {
    ElMessage.success(t('message.DelSuccess'))
  } else {
    ElMessage.error(res.msg)
  }
  delDialogVisible.value = false;
  getList();
};

// 套餐时间单位 国际化
function formatProductType(productType) {
  switch (productType) {
    case '1':
      return t('package.Years');
    case '2':
      return t('package.Months');
    case '3':
      return t('package.Days');
    case '4':
      return t('package.Hours');
  }
}

// 搜索方法
const onSubmit = (id, orderStatus) => {
  // 查询时把 pageIndex 重置为1
  pageIndex.value = 1
  getList(id, orderStatus);
}
// 清除  queryParams
const onClear = () => {
  queryParams.id = ''
  queryParams.orderStatus = ''
}

// 重置方法
const onReset = () => {
  onClear();
  getList();
}

// 分页
function handleSizeChange(val) {
  pageSize.value = val
  getList()
}

// 分页
function handleCurrentChange(val) {
  pageIndex.value = val
  getList(queryParams.id, queryParams.orderStatus)
}
</script>

<style scoped lang="less">
.queryBar {
  background-color: #fff;
  margin: .1rem 0;
  padding: .1rem 0;
  box-sizing: border-box;

  .demo-form-inline {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
  }

  .query_btns {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    margin: .15rem 0 0 0;
  }
}
</style>
